package com.foreknow.dao.impl;

import com.foreknow.dao.StudentDAO;
import com.foreknow.model.Student;

import java.sql.SQLException;

/**
 * StudentDAO接口的实现类
 */
public class StudentDAOImpl implements StudentDAO {
  //定义一个保存学生信息的数组(容器)
  private Student[] students;
  int count;

  //可以使用构造器对这个数组进行初始化
  public StudentDAOImpl() {
    students = new Student[10];//初始化数组容器
  }

  @Override
  public void addStudent(Student stu) throws SQLException {
    if (stu != null) {
      if (count < 6) {
        //如果条件成立，就要将这个学生对象student保存到数组中
        students[count] = stu;
        count++;
        System.out.println("添加成功......");
      } else {
        System.out.println("添加失败......");
      }
    }
  }

  @Override
  public Student queryById(String id) throws SQLException{
    Student stu = null;
    //需要对数组进行遍历
    for(int i = 0;i<count;i++){
      //如何从数组中获取元素(通过下标)
      if(students[i]!=null){
        //判断数组中某一个对象的id是否与输入参数id相同
        if(students[i].getId().equals(id)) {
          stu = students[i];
        }
      }
    }
    return stu;
  }

  @Override
  public Student[] getQueryAll() throws SQLException{
    //新创建一个数组容器
    Student[] stus = new Student[10];
    //对原有的数组进行遍历
    for(int i = 0;i<students.length;i++) {
      stus[i] = students[i];
    }
    return stus;
  }

  @Override
  public boolean updateStudent(Student student) throws SQLException{
    return false;
  }

  @Override
  public boolean deleteById(String id) throws SQLException{
    return false;
  }

  public static void main(String[] args) {
    StudentDAO dao = new StudentDAOImpl();

    Student student = new Student();
    student.setId("1000");
    student.setName("tom");
    student.setAge(30);
    student.setSchool("foreknow");

    Student student2 = new Student();
    student2.setId("1002");
    student2.setName("tom2");
    student2.setAge(22);
    student2.setSchool("foreknow2");

    //添加学生的信息
    try {
      dao.addStudent(student);
      dao.addStudent(student2);
      //根据id获取到学生的信息
      Student stu = dao.queryById("1002");
      System.out.println(stu.getId()+"--"+stu.getName()+"--"+stu.getSchool());

      System.out.println("----------------------------------------------------");

      Student[] stus = dao.getQueryAll();
      for (int i = 0;i<stus.length;i++){
        Student s = stus[i];
        System.out.println(s.getId()+"--"+s.getName());
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }



  }

}
